package cn.iocoder.yudao.module.member.fans.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.pojo.vo.UserSimpleVO;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.api.member.user.MemberUserApi;
import cn.iocoder.yudao.module.member.fans.service.MemberFansService;
import cn.iocoder.yudao.module.member.fans.vo.MemberFansPageReqVO;
import cn.iocoder.yudao.module.member.fans.vo.MemberFansRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 粉丝")
@RestController
@RequestMapping("/member/fans")
@Validated
public class MemberFansController {

    @Resource
    private MemberFansService memberFansService;
    @Resource
    private MemberUserApi memberUserApi;

    @GetMapping("/page")
    @Operation(summary = "获得视频粉丝分页")
    @PreAuthorize("@ss.hasAnyRoles('super_admin', 'platform_admin', 'tenant_admin')")
    public CommonResult<PageResult<MemberFansRespVO>> getFansPage(@Valid MemberFansPageReqVO pageReqVO) {
        PageResult<MemberFansRespVO> pageResult = memberFansService.getFansPage(pageReqVO);
        List<MemberFansRespVO> list = pageResult.getList();
        if (CollUtil.isEmpty(list)) {
            return success(PageResult.empty());
        }
        Set<Long> userIds = new HashSet<>();
        userIds.addAll(list.stream().map(MemberFansRespVO::getUserId).collect(Collectors.toSet()));
        userIds.addAll(list.stream().map(MemberFansRespVO::getFansUserId).collect(Collectors.toSet()));
        List<UserSimpleVO> users = memberUserApi.getUserSimpleList(userIds);
        list.forEach(item -> {
            item.setUser(users.stream().filter(user -> Objects.equals(user.getId(), item.getUserId())).findFirst().orElse(null));
            item.setFansUser(users.stream().filter(user -> Objects.equals(user.getId(), item.getFansUserId())).findFirst().orElse(null));
        });
        return success(pageResult);
    }

}
